package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;
/**
 * 老虚充接口
 * **/
@Slf4j
public class Plugin_ECARD_P008 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){

        try {

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));
            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("UserId",  apiConfig.getString("USERID"));
            dataParams.put("BizType", "ECARD");
            dataParams.put("OrderNo", dataConfig.getString("ChannelOrderCode"));
            dataParams.put("ProductId", dataConfig.getString("SUPProductId"));
            dataParams.put("BuyNum", "1");
            dataParams.put("AccountVal", dataConfig.getString("AccountVal"));
            dataParams.put("Phone", dataConfig.getString("AccountVal"));
            dataParams.put("Service", "SubmitOrder");
            dataParams.put("Time", String.valueOf(System.currentTimeMillis()));

            String str = getSignStr(dataParams);


            String sign = stringToMD5(str + apiConfig.getString("SecretKey"));
            dataParams.put("Sign", sign.toLowerCase());



            String url=apiConfig.getString("SubmitURL");

            String responseContent = HttpTool.sendPost(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("msg");
            String status = retobj.getString("status");
            if (code.equals("0") && status.equals("ok")) {
                String OrderStatus = retobj.getString("OrderStatus");
                if (OrderStatus.equals("SUCCESS")) {
                    return ChannelResult.success("充值成功");
                } else if (OrderStatus.equals("FAILED")) {
                    return ChannelResult.FAILED();
                } else if (OrderStatus.equals("UNDERWAY")) {
                    return ChannelResult.IN_PROCESS();
                }
                return  ChannelResult.error(OrderStatus);
            }else if (code.equals("108")){
                return ChannelResult.IN_PROCESS();
            }else if (code.equals("999")){
                return ChannelResult.IN_PROCESS();
            }
            else {
                return ChannelResult.FAILED(status+","+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("虚充提交订单接口错误：",ex);
            return  ChannelResult.error("虚充提交订单接口错误");
        }
    }

    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data) {
        try {



            Map dataParams = new LinkedHashMap<String, String>();
            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            dataParams.put("UserId",  apiConfig.getString("USERID"));
            dataParams.put("BizType", "ECARD");
            dataParams.put("OrderNo", dataConfig.getString("ChannelOrderCode"));
            dataParams.put("Service", "QueryOrder");
            dataParams.put("Time", String.valueOf(System.currentTimeMillis()));
            String str = getSignStr(dataParams);


            String sign = stringToMD5(str + apiConfig.getString("SecretKey"));
            dataParams.put("Sign", sign.toLowerCase());



            String url = apiConfig.getString("QueryURL");
            String responseContent = HttpTool.sendPost(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("msg");
            String status = retobj.getString("status");
            if (code.equals("0") && status.equals("ok")) {
                String OrderStatus = retobj.getString("OrderStatus");
                if (OrderStatus.equals("SUCCESS")) {
                    return ChannelResult.success("充值成功");
                } else if (OrderStatus.equals("FAILED")) {
                    return ChannelResult.FAILED();
                } else if (OrderStatus.equals("UNDERWAY")) {
                    return ChannelResult.IN_PROCESS();
                }else  if (OrderStatus.equals("NOTEXIST")){
                    return ChannelResult.error(status+","+msg);
                }
                return  ChannelResult.error(OrderStatus);
            }else {
                return ChannelResult.error(status+","+msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("虚充查询订单接口错误：", ex);
            return ChannelResult.error("虚充查询订单接口错误");
        }
    }


    public  ChannelResult Notify(JSONObject apiConfig,Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }


    /**
     * Description:MD5工具生成token
     *
     * @param plainText
     * @return
     */
    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        StringBuilder md5code = new StringBuilder();
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes("UTF-8"));
            md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
            while (md5code.length() < 32) {
                md5code.insert(0, "0");
            }
        } catch (Exception ex) {
            log.error("md5加密异常：" + ex.getMessage(), ex);
        }

        return md5code.toString();
    }


    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
}
